﻿using System.Globalization;
using System.Text.RegularExpressions;

namespace Devonline.Core;

/// <summary>
/// 用于金额转换的格式化实现
/// 预定义格式包括 ￥ 和任意大小写字母
/// ￥: 输出整数金额后缀 "整" 字, 默认不带 "整" 字
/// 大小写字母: 对应输出 圆 和 元, 默认大写
/// </summary>
public class MoneyFormatter : IFormatProvider, ICustomFormatter
{
    /// <summary>
    /// decimal format
    /// </summary>
    private const string FORMAT = "#L#E#D#C#K#E#D#C#J#E#D#C#I#E#D#C#H#E#D#C#G#E#D#C#F#E#D#C#.0B0A";

    /// <summary>
    /// 格式化方法
    /// </summary>
    /// <param name="format"></param>
    /// <param name="arg"></param>
    /// <param name="formatProvider"></param>
    /// <returns></returns>
    public string Format(string? format, object? arg, IFormatProvider? formatProvider)
    {
        if (arg?.GetType().GetCoreType() != typeof(decimal))
        {
            try
            {
                return arg switch
                {
                    IFormattable formattable => formattable.ToString(format, CultureInfo.CurrentCulture),
                    _ => arg?.ToString() ?? string.Empty
                };
            }
            catch (FormatException e)
            {
                throw new FormatException(string.Format("The format of '{0}' is invalid.", format), e);
            }
        }

        var result = string.Empty;
        if (arg is not null)
        {
            result = Convert.ToDecimal(arg).ToString(FORMAT);
            result = Regex.Replace(result, @"(((?<=-)|(?!-)^)[^1-9]*)|((?'z'0)[0A-E]*((?=[1-9])|(?'-z'(?=[F-L\.]|$))))|((?'b'[F-L])(?'z'0)[0A-L]*((?=[1-9])|(?'-z'(?=[\.]|$))))", "${b}${z}");
            result = Regex.Replace(result, ".", x => "负圆空零壹贰叁肆伍陆柒捌玖空空空空空空空分角拾佰仟万亿兆京垓秭穰"[x.Value[0] - '-'].ToString());

            if (!string.IsNullOrWhiteSpace(format))
            {
                if (format.Any(x => x == '￥'))
                {
                    result = Regex.Replace(result, "圆$", "圆整");
                }

                if (format.Any(x => x != '￥' && char.IsLower(x)))
                {
                    result = Regex.Replace(result, "圆", "元");
                }
            }
        }

        return result;
    }

    /// <summary>
    /// 格式化类型实现
    /// </summary>
    /// <param name="formatType"></param>
    /// <returns></returns>
    public object? GetFormat(Type? formatType) => formatType == typeof(ICustomFormatter) ? this : null;
}